﻿using itk.simple;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ImageDomain.Ob;

namespace ImageDomain.Utils;
public class ReadUtil
{

    #region Singleton 懒加载单例模式
    private ReadUtil() { }

    private static readonly Lazy<ReadUtil> Lazy = new(() => new ReadUtil());

    public static ReadUtil Instance => Lazy.Value;

    #endregion

    /// <summary>
    /// 
    /// </summary>
    /// <param name="files"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Image ReadImage(IList<string> files)
    {
        if (files?.Count == 0) throw new Exception("序列数目为0");

        var fileList = new List<SortDcm>();

        foreach (var file in files)
        {
            var image = SimpleITK.ReadImage(file, PixelIDValueEnum.sitkInt32);

            var inNum = image.GetMetaData("0020|0013");

            var sdcm = new SortDcm() { InstanceNumber = int.Parse(inNum), FileName = file };

            fileList.Add(sdcm);
        }

        var sortFiles = fileList.OrderBy(fi => fi.InstanceNumber).Select(fi => fi.FileName).ToList();

        var itkImage = SimpleITK.ReadImage(new VectorString(sortFiles), PixelIDValueEnum.sitkInt32);

        //itkImage.SetDirection(new VectorDouble() { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 });

        return itkImage;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="files"></param>
    /// <returns></returns>
    public async Task<Image> ReadImageAsync(IList<string> files) => await Task.Run(() => ReadImage(files));

    /// <summary>
    /// 
    /// </summary>
    /// <param name="dir"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Image ReadImage(string file, bool isMask = false)
    {
        if (!file.Contains("nii.gz") && !file.Contains("mha") && !file.Contains("mhd"))
            throw new Exception("仅支持 nii.gz mha mhd");

        var itkImage = isMask ? SimpleITK.ReadImage(file, PixelIDValueEnum.sitkInt8) : 
            SimpleITK.ReadImage(file, PixelIDValueEnum.sitkInt32);
        //itkImage.SetDirection(new VectorDouble() { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 });
        return itkImage;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="dirPath"></param>
    /// <returns></returns>
    public async Task<Image> ReadImageAsync(string file, bool isMask = false) => await Task.Run(() => ReadImage(file, isMask));


}
